package function;

import boot.Boot;

public class Navigator {

	private ChainMp3 currentMp3;
	private NavigatorSaver saver;

	public Navigator(Mp3File aCurrent) {
		super();
		currentMp3 = new ChainMp3Impl(aCurrent, null, null);
		saver = new NavigatorSaver(currentMp3);
		saver.save();
	}

	public Navigator(boolean reloadMode) {
		if (reloadMode) {
			try {
				NavigatorReloader reloader = new NavigatorReloader();
				currentMp3 = reloader.getReloadedData();
				gotoLast();
			} catch (NoDataException e) {
				currentMp3 = null;
			}
		} else {
			currentMp3 = null;
		}
		saver = new NavigatorSaver(currentMp3);
		saver.save();
	}

	private void gotoLast() {
		while (currentMp3.hasNext()) {
			currentMp3 = currentMp3.getNext();
		}
	}

	public Mp3File gotoPrevious() {
		ChainMp3 previous = currentMp3.getPrevious();
		if (previous != null) {
			currentMp3 = previous;
		}
		return currentMp3.getMp3File();
	}

	public Mp3File gotoNext() {
		ChainMp3 next = currentMp3.getNext();
		if (next != null) {
			currentMp3 = next;
		}
		return currentMp3.getMp3File();
	}

	public void setLast(Mp3File mp3) {
		ChainMp3 localCurrent = currentMp3;
		while (localCurrent.getNext() != null) {
			localCurrent = localCurrent.getNext();
		}
		ChainMp3 newChainMp3 = new ChainMp3Impl(mp3, localCurrent, null);
		localCurrent.setNext(newChainMp3);
		saver.save();
	}

	public void setCurrent(Mp3File mp3) {
		ChainMp3 newMp3 = new ChainMp3Impl(mp3, currentMp3, null);
		if (currentMp3 != null) {
			currentMp3.setNext(newMp3);
		}
		currentMp3 = newMp3;
		saver.save();
	}

	public Mp3File getPrevious() throws EmptyNavigatorException {
		if (currentMp3 == null) {
			throw new EmptyNavigatorException();
		}
		if (currentMp3.getPrevious() == null) {
			return null;
		}
		return currentMp3.getPrevious().getMp3File();
	}

	public Mp3File getNext() throws EmptyNavigatorException {
		if (currentMp3 == null) {
			throw new EmptyNavigatorException();
		}
		if (currentMp3.getNext() == null) {
			return null;
		}
		return currentMp3.getNext().getMp3File();
	}

	public Mp3File getCurrentMp3File() throws EmptyNavigatorException {
		if (currentMp3 == null) {
			throw new EmptyNavigatorException();
		}
		return currentMp3.getMp3File();
	}

	public boolean hasNext() {
		return (currentMp3 != null) && (currentMp3.getNext() != null);
	}

	public void removeCurrent() throws EmptyNavigatorException {
		if (currentMp3 == null) {
			throw new EmptyNavigatorException();
		}
		currentMp3 = currentMp3.getPrevious();
		if (currentMp3 != null) {
			currentMp3.setNext(null);
		} else {
			currentMp3 = null;
			throw new EmptyNavigatorException();
		}
	}

	public void savePlaylist(String name) {
		saver.savePlaylist(name);
	}

	public void loadPlaylist(String name) {
		NavigatorReloader reloader = new NavigatorReloader();
		try {
			currentMp3 = reloader.getPlaylist(name);
		} catch (NoDataException e) {
			Boot.debugErrorAlert("Playlist not found");
		}
	}
}
